﻿
using AutoMapper;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Dto;
using TransformerManager.Shared.Dto.Accessories;
using TransformerManager.Shared.Dto.AccessoryEquipment;
using TransformerManager.Shared.Dto.ActivePart;
using TransformerManager.Shared.Dto.BasicInfos;
using TransformerManager.Shared.Dto.Bushing;
using TransformerManager.Shared.Dto.Conservator;
using TransformerManager.Shared.Dto.CoolEquComp;
using TransformerManager.Shared.Dto.DiscWinding;
using TransformerManager.Shared.Dto.Dome;
using TransformerManager.Shared.Dto.HVRWinding;
using TransformerManager.Shared.Dto.LayerWinding;
using TransformerManager.Shared.Dto.Lead;
using TransformerManager.Shared.Dto.LeadConnector;
using TransformerManager.Shared.Dto.Tank;
using TransformerManager.Shared.Dto.TapChanger;
using TransformerManager.Shared.Dto.Transformer;
using TransformerManager.WPF.Common.Helper;
using TransformerManager.WPF.Common.Helper.Events;
using TransformerManager.WPF.Common.Http.Service;
using TransformerManager.WPF.Common.Views;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.CreateModule.ViewModels
{
    public class CreateNewProjectViewModel : BindableBase, INavigationAware
    {

        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private readonly ITransformerService _transformerService;
        private readonly IMapper _mapper;

        private NavigationContext _navigationContext;
        public CreateNewProjectViewModel(
            IMapper mapper,
            IRegionManager regionManager,
            ITransformerService transformerService,
            IEventAggregator eventAggregator)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _transformerService = transformerService;
            _mapper = mapper;

            InitAllCmd();
        }

        #region Command

        public DelegateCommand<string> UpdateDoneCmd { private set; get; }

        public DelegateCommand CheckCmd { private set; get; }

        #endregion


        #region 方法的定义

        private string _projectNumber;
        public string ProjectNumber
        {
            set
            {
                _projectNumber = value;

                RaisePropertyChanged();
            }
            get
            {
                return _projectNumber;
            }
        }

        private TransformerDto _transformerDto;
        public TransformerDto TransformerDto
        {
            set
            {
                _transformerDto = value;

                RaisePropertyChanged();
            }
            get
            {
                return _transformerDto;
            }
        }

        private Visibility isLodingVisible = Visibility.Collapsed;
        public Visibility IsLodingVisible
        {
            set
            {
                isLodingVisible = value;

                RaisePropertyChanged();
            }
            get
            {
                return isLodingVisible;
            }
        }

        private Visibility _isCreateContentVisible = Visibility.Collapsed;
        public Visibility IsCreateContentVisible
        {
            set
            {
                _isCreateContentVisible = value;

                RaisePropertyChanged();
            }
            get
            {
                return _isCreateContentVisible;
            }
        }

        private bool _isTbProjNumberEditable = true;
        public bool IsTbProjNumberEditable
        {
            get { return _isTbProjNumberEditable; }
            set { _isTbProjNumberEditable = value; RaisePropertyChanged(); }
        }

        private bool _isBtnCheckProjectEditable = true;
        public bool IsBtnCheckProjectEditable
        {
            get { return _isBtnCheckProjectEditable; }
            set { _isBtnCheckProjectEditable = value; RaisePropertyChanged(); }
        }

        private bool _isBtnDoneEditable = false;
        public bool IsBtnDoneEditable
        {
            get { return _isBtnDoneEditable; }
            set { _isBtnDoneEditable = value; RaisePropertyChanged(); }
        }

        #endregion


        #region 函数的定义

        private void InitAllCmd()
        {
            UpdateDoneCmd = new DelegateCommand<string>(CreateTransformerInfo);

            CheckCmd = new DelegateCommand(async () =>
            {

                IsLodingVisible = Visibility.Visible;

                await CheckProjectNumberValid();

                IsLodingVisible = Visibility.Collapsed;
            });
        }

        public async void CreateTransformerInfo(string projectNumber)
        {
            var dialogResult = HandyControl.Controls.MessageBox.Show(
                "是否完成编辑?",
                "确认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (dialogResult == MessageBoxResult.No) return;

            _transformerDto.BasicInfos.ProjectNumber = projectNumber;

            // 请求数据
            var result = await _transformerService.AddTransformerAsync(_transformerDto);
            if (!result.Success)
            {
                hc.Growl.Error(
                        $"响应信息: {result.Message}",
                        "Notification");
                return;
            }
            hc.Growl.Success($"响应信息：{result.Message}", "Notification");

            // UI 变换
            IsTbProjNumberEditable = false;
            IsBtnCheckProjectEditable = false;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(false);
        }

        private async Task CheckProjectNumberValid()
        {
            if (string.IsNullOrEmpty(ProjectNumber))
                return;

            Regex regex = new Regex(@"^\d{6}$");
            var match = regex.Match(ProjectNumber);
            if (!match.Success)
            {
                hc.MessageBox.Show(
                    "项目号不符合要求!",
                    "错误",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            // 请求数据
            var result = await _transformerService.CheckProjectNumberExistAsync(ProjectNumber);
            if (!result) return;

            TransformerDto = new TransformerDto()
            {
                UserId = null,
                BasicInfos =
                    new BasicInfosDto
                    {
                        ProjectNumber = ProjectNumber,
                        ProjectName = string.Empty,
                        ProjectStatus = "NotStarted",
                        RefProjectNumber = string.Empty,
                        ApplicationType = "NetworkTransformer",
                        NumOfUnits = 1,
                        Capacity = 50,
                        RatedFrequency = 50,
                        VectorGroupSym = "YNd11",
                        RatedHV = 110,
                        RatedLV = 35,
                        ManufactureDate = DateTime.UtcNow,
                        MaterialNumber = string.Empty,
                        NumberOfPhases = 3,
                        RegionType = "Domestic",
                        ProdTag = string.Empty,
                        Housing = "Outdoor",
                        InsulationMaterial = "MineralOil",
                        TotalMass = 0,
                        Length = 0,
                        Width = 0,
                        Height = 0,
                        TapChangers = new ObservableCollection<TapChangerDto>(),
                        Domes = new ObservableCollection<DomeDto>(),
                        Bushings = new ObservableCollection<BushingDto>()
                    },
                Tank = new TankDto
                {
                    TankLength = 0,
                    TankWidth = 0,
                    TankHeight = 0,
                    TankShape = string.Empty,
                    FrameType = string.Empty,
                    RadButterflyValveType = string.Empty,
                    OltcIndent = string.Empty,
                    HVLVIndent = string.Empty,
                    ActbDome = string.Empty,
                    OctbDome = string.Empty,
                    HasWheel = false,
                    HasNeutralDome = false
                },
                Conservator = new ConservatorDto
                {
                    ConservatorType = string.Empty,
                    HasTCConservator = false,
                    Dimension = string.Empty,
                },
                CoolingSystem = new CoolingSystemDto
                {
                    CoolingType = string.Empty,
                    CoolingLayout = string.Empty,
                    RadiatorType = string.Empty,
                    RadiatorManufacturer = string.Empty,
                    FanType = string.Empty,
                    FanManufacturer = string.Empty,
                    CoolerType = string.Empty,
                    CoolerManufacturer = string.Empty,
                },
                Accessories = new AccessoriesDto
                {
                    BoltMaterial = string.Empty,
                    SealMaterial = string.Empty,
                    AccesstoryEquipments = new ObservableCollection<AccessoryEquipmentDto>()
                },
                Lead = new LeadDto
                {
                    HVCurrent = 0,
                    LVCurrent = 0,
                    MVCurrent = 0,
                    IsCenterInfeed = false,
                    HVOutlet = string.Empty,
                    HVROutlet = string.Empty,
                    LVOutlet = string.Empty,
                    MVOutlet = string.Empty,
                    HVBushingPos = string.Empty,
                    LVBushingPos = string.Empty,
                    MVBushingPos = string.Empty,
                    LeadConnectors = new ObservableCollection<LeadConnectorDto>()
                },
                Winding = new WindingDto
                {
                    HVRWindings = new ObservableCollection<HVRWindingDto>(),
                    DiscWindings = new ObservableCollection<DiscWindingDto>(),
                    LayerWindings = new ObservableCollection<LayerWindingDto>()
                },
                ActivePart = new ActivePartDto
                {
                    StripNumber = -1,
                    SpacerNumber = -1,
                    RatedVotage = -1,
                    IsCenterInfeed = false,
                    IsUniformInsulation = false,
                    WindingNumber = -1,
                    HVRType = string.Empty,
                    InnestWindingType = string.Empty,
                    HVAC = -1,
                    HasOD = false
                },
                CreateTime = DateTime.UtcNow

            };

            _regionManager.RequestNavigate("CreateNewProjectRegion", nameof(ProjectInfoTemplate));
            CustomiseRegionManager.PreLoadRegions(_regionManager);

            // UI 变换
            IsCreateContentVisible = Visibility.Visible;
            IsTbProjNumberEditable = false;
            IsBtnCheckProjectEditable = false;
            IsBtnDoneEditable = true;

            // 通知详情页面可以编辑
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(true);
        }

        #endregion


        #region 接口实现的函数

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            _navigationContext = navigationContext;
            // UI 变换
            IsCreateContentVisible = Visibility.Hidden;
            IsTbProjNumberEditable = true;
            IsBtnCheckProjectEditable = true;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(true);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            _navigationContext = navigationContext;
            // UI 变换
            IsCreateContentVisible = Visibility.Hidden;
            IsTbProjNumberEditable = true;
            IsBtnCheckProjectEditable = true;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(false);

            CustomiseRegionManager.RemoveRegions(navigationContext);
        }

        #endregion

    }
}
